<script setup>
import { ref, onMounted, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { getMyInfoApi, myTeamApi } from "@/api/public";
import { useConfigStore } from "@/store/modules/config";
import { showFailToast, showSuccessToast, showToast } from "vant";
import AppHeader from "@/components/app_header.vue";
import { fromWeiToFloat, encryptAddress } from "@/utils";
import Decimal from "decimal.js";

const useConfig = useConfigStore();

const { locale, t } = useI18n();
const isBindWallte = ref(true);
const isShow = ref(false);
const loading = ref(false);
const finished = ref(false);
const router = useRouter();
const address = ref("");

const ToBlack = () => {
  router.push("home");
};
const ToRecord = () => {
  router.push("record");
};
/// ======================bigv

// {
//   "id": 3,
//   "address": "0xcede577cf48140319e74e75eacaf854064340ff9", //自己地址
//   "referrer_address": "0x549cd67e765ca156ba149b8c6bbd29cb7eccef00", //上级地址
//   "power": "0", //自己算力
//   "powerd_at": "2024-09-27 13:13:53", //最近算力分红时间
//   "created_at": "2024-09-14 18:07:01", //注册时间
//   "updated_at": "2024-10-06 22:16:50",
//   "asset_cbt": {
//     "id": 3,
//     "address": "0xcede577cf48140319e74e75eacaf854064340ff9", //自己地址
//     "balance": "65000000000000000", //余额
//     "freeze": "0", //冻结(一般不用)
//     "pledge": "1000000000000000000000", //质押量
//     "team_pledge": "20000000000000000", //团队业绩
//     "pledge_output_at": "2024-10-09 11:35:14", //最近持币分红时间
//     "created_at": "2024-09-21 16:27:03",
//     "updated_at": "2024-10-09 15:33:26"
//   }, //cpt资产
//   "nft_num": 0, //nft数量
//   "before_hold_profit": "0", //持币收益
//   "before_extension_profit": "0", //推广收益
//   "before_nft_profit": "0", //nft收益
//   "total_profit": "0" //累计总收益
// }

const userData = reactive({
  address: "",
  referrer_address: "",
  power: "",
  powerd_at: "",
  created_at: "",
  updated_at: "",
  asset_cbt: { balance: "" },
  asset_nft: { balance: "" },
  asset_dynamic: { balance: "" },
  before_dynamic_profit: "0",
  nft_num: 0,
  before_hold_profit: "0",
  before_extension_profit: "0",
  before_nft_profit: "0",
  total_profit: "0"
});

// 今日总收益
const totalRevenue = computed(() => {
  try {
    const before_nft_profit = fromWeiToFloat(userData.before_nft_profit);
    const before_hold_profit = fromWeiToFloat(userData.before_hold_profit);
    const before_extension_profit = fromWeiToFloat(
      userData.before_extension_profit
    );
    const before_dynamic_profit = fromWeiToFloat(
      userData.before_dynamic_profit
    );

    const a = Decimal(before_nft_profit).add(Decimal(before_hold_profit));
    const b = Decimal(a).add(Decimal(before_extension_profit));
    const c = Decimal(b).add(Decimal(before_dynamic_profit));
    return c.toFixed(4);
  } catch (error) {
    return 0;
  }
});

const shareURL = computed(() => {
  const origin = location.origin;
  return `${origin}/#/home?address=${useConfig.account}`;
});

const getMyInfo = async () => {
  const params = {
    // address: "0x549Cd67E765CA156BA149b8c6bbD29CB7ECCEf00" //useConfig.account
    address: useConfig.account
  };
  const res = await getMyInfoApi(params);
  Object.assign(userData, res);
  console.log(res);
};

// 获取上级地址
// const referrer_address = ref("--");
// const getInvitationRelationship = async () => {
//   if (!useConfig.getAccount) {
//     return;
//   }

//   const addr = await useConfig.getMasterContract.methods
//     .getInvitationRelationship(useConfig.getAccount)
//     .call();

//   referrer_address.value = addr;
// };

// const butDisabled = ref(false);
const withdrawalFn = async () => {
  // if (butDisabled.value) return;
  // 当可提现余额为0时，无法提现
  if (fromWeiToFloat(userData.asset_cbt.balance) <= 0) return;
  const minDeposit = await useConfig.masterContract.methods.minDeposit().call();

  console.log("minDeposit", minDeposit);

  const params = {
    to: useConfig.masterContractAddress,
    from: useConfig.getAccount,
    value: minDeposit
  };

  try {
    const gasLimit = await useConfig.getWbe3.eth.estimateGas(params);
    params.gas = useConfig.getWbe3.utils.toHex(gasLimit);
  } catch (error) {
    params.gas = useConfig.getWbe3.utils.toHex(200000);
  }

  // butDisabled.value = true;
  useConfig.getWbe3.eth
    .sendTransaction(params)
    .on("transactionHash", hash => {
      console.log("hash", hash);
      showSuccessToast(t("bigv.success"));
    })
    .on("receipt", receipt => {
      console.log("receipt", receipt);
      // butDisabled.value = false;
    })
    .catch(error => {
      // butDisabled.value = false;
      showToast(error.data.message);
      console.error("error:", error.data);
    });

  console.log("产出 提现");
};

// nft 提现
const nftWithdrawalFn = async () => {
  // if (butDisabled.value) return;
  // 当可提现余额为0时，无法提现
  if (fromWeiToFloat(userData.asset_nft.balance) <= 0) return;
  const minDeposit = await useConfig.nftTotalContract.methods
    .minDeposit()
    .call();

  console.log("minDeposit", minDeposit);

  const params = {
    to: useConfig.nftTotalContractAddress,
    from: useConfig.getAccount,
    value: minDeposit
  };

  try {
    const gasLimit = await useConfig.getWbe3.eth.estimateGas(params);
    params.gas = useConfig.getWbe3.utils.toHex(gasLimit);
  } catch (error) {
    params.gas = useConfig.getWbe3.utils.toHex(200000);
  }

  // butDisabled.value = true;
  useConfig.getWbe3.eth
    .sendTransaction(params)
    .on("transactionHash", hash => {
      console.log("hash", hash);
      showSuccessToast(t("bigv.success"));
    })
    .on("receipt", receipt => {
      console.log("receipt", receipt);
      // butDisabled.value = false;
    })
    .catch(error => {
      // butDisabled.value = false;
      showToast(error.data.message);
      console.error("error:", error.data);
    });

  console.log("nfc 提现");
};

// 动态 提现
const dynamicWithdrawalFn = async () => {
  // if (butDisabled.value) return;
  // 当可提现余额为0时，无法提现
  if (fromWeiToFloat(userData.asset_dynamic.balance) <= 0) return;
  const minDeposit = await useConfig.dynamicTotalContract.methods
    .minDeposit()
    .call();

  console.log("minDeposit", minDeposit);

  const params = {
    to: useConfig.dynamicTotalContractAddress,
    from: useConfig.getAccount,
    value: minDeposit
  };

  try {
    const gasLimit = await useConfig.getWbe3.eth.estimateGas(params);
    params.gas = useConfig.getWbe3.utils.toHex(gasLimit);
  } catch (error) {
    params.gas = useConfig.getWbe3.utils.toHex(200000);
  }

  // butDisabled.value = true;
  useConfig.getWbe3.eth
    .sendTransaction(params)
    .on("transactionHash", hash => {
      console.log("hash", hash);
      showSuccessToast(t("bigv.success"));
    })
    .on("receipt", receipt => {
      console.log("receipt", receipt);
      // butDisabled.value = false;
    })
    .catch(error => {
      // butDisabled.value = false;
      showToast(error.data.message);
      console.error("error:", error.data);
    });

  console.log("nfc 提现");
};

const teamList = ref([]);
const myTeam = async () => {
  const params = {
    address: useConfig.account
  };
  const res = await myTeamApi(params);
  // const _res = [
  //   {
  //     id: 5,
  //     address: "0xf0d1b1d745eb2a0f3ebab9b7eb7e983f3142472d",
  //     referrer_address: "0x549cd67e765ca156ba149b8c6bbd29cb7eccef00",
  //     power: "0",
  //     powerd_at: "2024-10-09 14:26:16",
  //     created_at: "2024-10-09 14:26:16",
  //     updated_at: "2024-10-09 14:32:59",
  //     dapp_asset: {
  //       id: 5,
  //       address: "0xf0d1b1d745eb2a0f3ebab9b7eb7e983f3142472d",
  //       balance: "65000000000000000",
  //       freeze: "0",
  //       pledge: "1000000000000000000000",
  //       team_pledge: "1000000000000000000000",
  //       pledge_output_at: "2024-10-09 11:35:14",
  //       created_at: "2024-09-20 15:03:42",
  //       updated_at: "2024-10-09 15:33:26"
  //     }
  //   }
  // ];
  teamList.value = res;
  console.log("团队");
  console.log(res);
};

// 格式化上级地址
const formatTopAddress = val => {
  if (!val) return "--";
  if (val.length > 12) {
    return val.substring(0, 4) + "****" + val.substring(val.length - 8);
  }
  return val;
};
// 格式化分享地址shareURL
const formatShareURL = val => {
  if (!val) return "--";
  if (val.length > 20) {
    return val.substring(0, 20) + "...";
  }
  return val;
};
// 复制功能
const copyText = val => {
  var aux = document.createElement("input");
  try {
    aux.setAttribute("value", val);
    document.body.appendChild(aux);
    aux.select();
    document.execCommand("Copy");
    document.body.removeChild(aux);
    showSuccessToast(t("revenue.success"));
  } catch (error) {
    showFailToast(t("revenue.fail"));
  }
};

onMounted(() => {
  getMyInfo();
  // getInvitationRelationship();
  myTeam();
});
</script>

<template>
  <div class="home div-container">
    <!-- header--start-->
    <div class="div-header">
      <div class="div-left" @click.stop="ToBlack">
        <img src="@/assets/icon-black.png" alt="" />
      </div>
      <span class="title">
        <img src="@/assets/icon-logo.png" width="40" alt="" />
      </span>
      <div class="div-right">...</div>
    </div>
    <!-- header--start-->
    <!-- div-wallet--start-->
    <AppHeader />
    <!--    <div class="div-wallet">-->
    <!--      <div class="wallet" @click.stop="showDialog">-->
    <!--        <img src="@/assets/icon-wallet.png" width="32" height="32" alt="" />-->
    <!--        0x02****27078d9d-->
    <!--      </div>-->
    <!--      <div class="div-change" @click="changeLang">-->
    <!--        <img src="@/assets/icon-change.png" width="19" height="19" alt="" />-->
    <!--        {{ $t("home.ch") }}-->
    <!--      </div>-->
    <!--    </div>-->
    <!-- div-wallet--end-->
    <!--div-out-link-start-->
    <div v-if="isBindWallte" class="out-link">
      <div class="link-box">
        <h4>{{ $t("revenue.myIncome") }}</h4>
        <div class="link-text" @click.stop="ToRecord">
          <span>{{ $t("record.record") }}</span>
          <van-icon name="arrow" />
        </div>
      </div>

      <div class="div-revenue">
        <van-list
          v-model="loading"
          :finished="finished"
          :finished-text="$t('pledge.noData')"
          @load="onLoad"
        >
          <van-cell class="green-bg">
            <span>
              {{ fromWeiToFloat(userData.asset_cbt.balance) || 0 }}
            </span>
            <span class="right-btn">
              <p>{{ $t("revenue.balanceIncome") }}</p>
              <p class="btn-withdraw" @click="withdrawalFn">
                {{ $t("record.tabs4") }}
              </p>
            </span>
          </van-cell>
          <!--可提出NFT分红-->
          <van-cell class="green-bg">
            <span>{{ fromWeiToFloat(userData.asset_nft.balance) || 0 }} </span>
            <span class="right-btn">
              <p>{{ $t("revenue.NFTDividends") }}</p>
              <p class="btn-withdraw" @click="nftWithdrawalFn">
                {{ $t("record.tabs4") }}
              </p>
            </span>
          </van-cell>
          <!--可提出动态分红-->
          <van-cell class="green-bg">
            <span
              >{{ fromWeiToFloat(userData.asset_dynamic.balance) || 0 }}
            </span>
            <span class="right-btn">
              <p>{{ $t("revenue.DynamicDividends") }}</p>
              <p class="btn-withdraw" @click="dynamicWithdrawalFn">
                {{ $t("record.tabs4") }}
              </p>
            </span>
          </van-cell>

          <van-cell>
            <span>{{ fromWeiToFloat(userData.before_hold_profit) }}</span>
            <span>{{ $t("revenue.holdingIncome") }}</span>
          </van-cell>
          <van-cell>
            <span>{{ fromWeiToFloat(userData.before_extension_profit) }}</span>
            <span>{{ $t("revenue.shareIncome") }}</span>
          </van-cell>
          <van-cell>
            <span>{{ fromWeiToFloat(userData.before_nft_profit) }}</span>
            <span>{{ $t("revenue.NFTIncome") }}</span>
          </van-cell>
          <!--动态分红-->
          <van-cell>
            <span>{{ fromWeiToFloat(userData.before_dynamic_profit) }}</span>
            <span>{{ $t("revenue.dividends") }}</span>
          </van-cell>

          <van-cell>
            <span>{{ totalRevenue }}</span>
            <span>{{ $t("revenue.todayIncome") }}</span>
          </van-cell>
          <van-cell class="gray-bg">
            <span>{{ fromWeiToFloat(userData.total_profit) }}</span>
            <span>{{ $t("revenue.totalIncome") }}</span>
          </van-cell>
        </van-list>
      </div>

      <!--      <div class="div-btn-paramy div-btn" @click="withdrawalFn">-->
      <!--        {{ $t("record.tabs4") }}-->
      <!--      </div>-->
    </div>

    <!--    我的团队-->
    <div class="div-team">
      <div class="div-team-title">{{ $t("revenue.revenueTransparent") }}</div>
      <div class="out-link">
        <h4>{{ $t("revenue.myTeam") }}</h4>
        <div class="div-revenue">
          <van-list
            v-model="loading"
            :finished="finished"
            :finished-text="$t('pledge.noData')"
            @load="onLoad"
          >
            <van-cell>
              <span>
                {{ formatTopAddress(useConfig.referrerAddress) }}
                <!--                <van-icon-->
                <!--                  v-show="useConfig.referrerAddress"-->
                <!--                  class="btn-copy"-->
                <!--                  color="#0283EF"-->
                <!--                  name="edit"-->
                <!--                  @click.stop="copyText(useConfig.referrerAddress)"-->
                <!--                />-->
              </span>
              <span>{{ $t("revenue.superiorAddress") }}</span>
            </van-cell>

            <van-cell>
              <span>
                {{ formatShareURL(shareURL) }}
                <img
                  v-show="shareURL"
                  src="./../../icons/svg/copy.svg"
                  width="16"
                  class="btn-copy"
                  alt=""
                  @click.stop="copyText(shareURL)"
                />
                <!--                <van-icon-->
                <!--                  v-show="shareURL"-->
                <!--                  class="btn-copy"-->
                <!--                  name="edit"-->
                <!--                  color="#0283EF"-->
                <!--                  @click.stop="copyText(shareURL)"-->
                <!--                />-->
              </span>
              <span>{{ $t("revenue.link") }}</span>
            </van-cell>
          </van-list>
        </div>
      </div>
    </div>

    <!--    团队列表-->
    <div class="div-team-list">
      <div class="out-link">
        <h4>{{ $t("revenue.teamList") }}</h4>
        <div class="list-box">
          <van-list
            v-model="loading"
            :finished="finished"
            :finished-text="$t('pledge.noData')"
            @load="onLoad"
          >
            <van-cell class="green-bg" :border="false">
              <span>{{ $t("revenue.address") }}</span>
              <span>{{ $t("revenue.performance") }}</span>
              <span>{{ $t("revenue.computingPower") }}</span>
            </van-cell>

            <div v-if="teamList.length === 0" class="div-list-empty">
              <img src="@/assets/icon-revenue-empty.png" width="150" alt="" />
              <p>{{ $t("pledge.tableEmpty") }}</p>
            </div>

            <van-cell
              v-for="(item, index) in teamList"
              :key="index"
              :border="false"
              :class="index % 2 == 1 ? 'dbstyle' : ''"
            >
              <span>{{ encryptAddress(item.address) }}</span>
              <span>{{ fromWeiToFloat(item.team_pledge) }}</span>
              <span>{{ item.power }}</span>
            </van-cell>

            <div v-show="false" class="div-list-empty">
              <img
                src="./../../assets/icon-revenue-empty.png"
                width="150"
                alt=""
              />
              <p>{{ $t("pledge.tableEmpty") }}</p>
            </div>
          </van-list>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
@import "./../../styles/mixin.less";
p {
  margin: 0px;
}
.home {
  font-size: 14px;
  color: #ffffff;
  padding-bottom: 20px;
}
.div-wallet {
  height: 44px;
  padding: 0 14px;
  display: flex;
  font-size: 14px;
  justify-content: space-between;
  & > div {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .wallet {
    padding-left: 10px;
    padding-right: 10px;
    border-radius: 20px;
    border: 1px solid #9cb3bf;
  }
}
.out-link {
  margin: 22px 10px;
  padding: 0px 22px;
  background: #27283e;
  border-radius: 20px;
  border: 1px solid #62737f;
  .link-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .link-text {
      color: #0d5bed;
      span {
        margin-right: 4px;
        vertical-align: text-bottom;
      }
    }
  }
  h4 {
    color: #e5f0f4;
    font-weight: 500;
    font-size: 18px;
    line-height: 24px;
  }
  :deep(.van-cell:after) {
    left: 0px;
  }
  .div-btn {
    margin-top: 20px;
    margin-bottom: 16px;
  }

  .div-revenue {
    min-height: 200px;
    :deep(.van-cell) {
      background: #2e2f4a;
      color: #e5f0f4;
      height: 50px;
      margin-bottom: 18px;
    }
    :deep(.van-cell.green-bg) {
      background: linear-gradient(57deg, #47ddc2 0%, #c1ffc8 100%);
      .van-cell__value {
        span {
          color: black;
        }
      }
    }
    :deep(.van-cell.gray-bg) {
      background: linear-gradient(57deg, #676978 0%, #2a2d41 100%);
      .van-cell__value {
        span:nth-child(1) {
          color: #ffffff;
        }
      }
    }
    :deep(.van-cell:after) {
      display: none;
    }
    :deep(.van-cell__value) {
      display: flex;
      justify-content: space-between;
      align-items: center;
      span:nth-child(1) {
        font-weight: 500;
        font-size: 14px;
        color: #ef9d7e;
        line-height: 20px;
        text-align: left;
      }
      span:nth-child(2) {
        font-size: 12px;
        color: #606374;
        font-weight: 500;
        white-space: nowrap;
      }
    }
    .btn-withdraw {
      vertical-align: -10px;
      margin-left: 10px;
    }
    .right-btn {
      p {
        margin-bottom: 0px;
        line-height: 18px;
        &.btn-withdraw {
          color: #4aa2f8;
        }
      }
    }
  }
}

.div-team {
  width: 100%;
  background-image: url("./../../assets/icon-home_bg.png");
  background-repeat: no-repeat;
  background-position: 26px 0;
  background-size: 82% auto;
  padding-top: 26px;
  .div-team-title {
    text-align: center;
    font-size: 18px;
    margin-bottom: 40px;
  }
  .out-link {
    background: none;
    .div-revenue {
      min-height: 160px;
      :deep(.van-cell__value) {
        span:nth-child(1) {
          color: #ffffff;
        }
      }
    }
  }
}
.div-team-list {
  .list-box {
    min-height: 200px;
    margin-bottom: 34px;
    :deep(.van-cell.dbstyle) {
      background: #4d5162;
    }
    :deep(.van-cell) {
      background: #383d50;
      margin-bottom: 0;
      height: 38px;
      font-size: 11px;
      .van-cell__value {
        span {
          display: inline-block;
          width: 30%;
          text-align: center;
          color: #ffffff;
        }
        span:nth-child(1) {
          width: 40%;
        }
        span:nth-child(2) {
          font-size: 11px;
        }
      }
    }
  }
  :deep(.van-cell.green-bg) {
    border-radius: 10px 10px 0 0;
    background: linear-gradient(57deg, #47ddc2 0%, #c1ffc8 100%);
    .van-cell__value {
      span {
        color: black;
        font-weight: 600;
      }
    }
  }
  .div-list-empty {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    min-height: 200px;
    p {
      font-size: 16px;
      color: #606374;
    }
  }
}
.btn-copy {
  cursor: pointer;
  margin-left: 10px;
  vertical-align: -2px;
}
</style>
